import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import *
from mainwindow import Ui_MainWindow
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from PyQt5 import QtCore, QtGui, QtWidgets
import re


class Action(Ui_MainWindow):
    def __init__(self, parent=None):
        super(Action, self).__init__(parent)
        self.setupUi(self)
        self.show()

    def ClickClear(self):
        self.plainTextEdit.clear()
        self.plainTextEdit_2.clear()
        self.plainTextEdit_3.clear()
        self.plainTextEdit_4.clear()
        self.plainTextEdit_5.clear()
        self.plainTextEdit_6.clear()
        self.plainTextEdit_7.clear()
        self.plainTextEdit_8.clear()
        self.plainTextEdit_9.clear()
        self.plainTextEdit_10.clear()
        self.plainTextEdit_11.clear()
        self.plainTextEdit_12.clear()
    
    def cb1(self):
        if self.checkBox.isChecked() == True:
            self.plainTextEdit.setEnabled(True)
            self.plainTextEdit_3.setEnabled(True)
            self.plainTextEdit_4.setEnabled(True)
        else:
            self.plainTextEdit.setEnabled(False)
            self.plainTextEdit_3.setEnabled(False)
            self.plainTextEdit_4.setEnabled(False)
 
    def cb2(self):
        if self.checkBox_2.isChecked() == True:
            self.plainTextEdit_2.setEnabled(True)
            self.plainTextEdit_5.setEnabled(True)
            self.plainTextEdit_6.setEnabled(True)
        else:
            self.plainTextEdit_2.setEnabled(False)
            self.plainTextEdit_5.setEnabled(False)
            self.plainTextEdit_6.setEnabled(False)
        
    
    def cb3(self):
        if self.checkBox_3.isChecked() == True:
            self.plainTextEdit_8.setEnabled(True)
            self.plainTextEdit_7.setEnabled(True)
            self.plainTextEdit_9.setEnabled(True)
        else:
            self.plainTextEdit_8.setEnabled(False)
            self.plainTextEdit_7.setEnabled(False)
            self.plainTextEdit_9.setEnabled(False)
            
    def cb4(self):
        if self.checkBox_4.isChecked() == True:
            self.plainTextEdit_11.setEnabled(True)
            self.plainTextEdit_10.setEnabled(True)
            self.plainTextEdit_12.setEnabled(True)
        else:
            self.plainTextEdit_11.setEnabled(False)
            self.plainTextEdit_10.setEnabled(False)
            self.plainTextEdit_12.setEnabled(False)
    
    def Paint(self):
        pixs = plt.figure(figsize=(6, 6))
 
        
        #函数1
        checkBox = self.checkBox.isChecked()
        X = []
        if checkBox == True:
            PT = self.plainTextEdit.toPlainText()
            if PT == '':
                QtWidgets.QMessageBox.critical(self, "错误", "请输入所需画图的公式")
            else:
                x1_1 = self.plainTextEdit_3.toPlainText()
                x1_2 = self.plainTextEdit_4.toPlainText()
                if x1_1 == '' or x1_2 =='':
                    QtWidgets.QMessageBox.critical(self, "错误", "请输入取值范围")
                else:
                    X.append(float(x1_1))
                    X.append(float(x1_2))
                    color1 = self.comboBox_5.currentText()
                    CB = self.comboBox.currentText()

                    if color1 == '红色':
                        color1 = 'red'
                    elif color1 == '蓝色':
                        color1 = 'blue'
                    elif color1 == '绿色':
                        color1 = 'green'
                    elif color1 == '紫色':
                        color1 = 'purple'
                    x = np.linspace(float(x1_1),float(x1_2), 1000)
                    if CB == '三角函数':
                        try:
                            y1 = eval('np.'+PT)
                            plt.plot(x,y1,label=PT,color = color1)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确的三角函数,乘号不能省略")
                    
         
                    elif CB == '圆':
                        if re.findall('[2](.+)[($]', PT)[0] == '-':
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确圆的方程,乘号不能省略")
                        else:
                            try:
                                yuan_x = -int(re.findall(r'x([-+]\d{1,})',PT)[0])
                                # print(yuan_x)
                            except:
                                yuan_x = 0
                            try:
                                yuan_y = -int(re.findall(r'y([-+]\d{1,})',PT)[0])
                                # print(yuan_y)
                            except:
                                yuan_y = 0
             
                            center = (yuan_x,yuan_y)
                            # print(center)
                            r = int(re.findall(r'=(\d{1,})',PT)[0])**(1/2)
                            # print(r)
                            # if center[0]-r <= float(x1_1) <= center[0]+r and center[0]-r <= float(x1_2) <= center[0]+r:
                            x = np.linspace(center[0] - r, center[0] + r, 5000)
                            y1 = np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            y2 = -np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            plt.plot(x, y1, c=color1,label = PT)
                            plt.plot(x, y2, c=color1)
       
                    else:
                        try:
                            plt.plot(x, eval(PT),label = PT,color = color1)
                            plt.xlim(x.min(),x.max())
                            plt.ylim(x.min(),x.max())
                            plt.legend('best')
                        except :
                            QtWidgets.QMessageBox.critical(self, "错误", "非法表达式,乘号不能省略")
            
                
        #函数2
        checkBox2 = self.checkBox_2.isChecked()
        if checkBox2 == True:
            PT1 = self.plainTextEdit_2.toPlainText()
            if PT1 == '':
                QtWidgets.QMessageBox.critical(self, "错误", "请输入所需画图的公式")
            else:
                x2_1 = self.plainTextEdit_5.toPlainText()
                x2_2 = self.plainTextEdit_6.toPlainText()
                if x1_1 == '' or x1_2 =='':
                    QtWidgets.QMessageBox.critical(self, "错误", "请输入取值范围")
                else:
                    X.append(float(x2_1))
                    X.append(float(x2_2))
                    color2 = self.comboBox_6.currentText()
                    CB2 = self.comboBox_2.currentText()
                    if color2 == '红色':
                        color2 = 'red'
                    elif color2 == '蓝色':
                        color2 = 'blue'
                    elif color2 == '绿色':
                        color2 = 'green'
                    elif color2 == '紫色':
                        color2 = 'purple'
                    x = np.linspace(float(x2_1),float(x2_2), 1000)
                    if CB2 == '三角函数':
                        try:
                            y2 = eval('np.'+PT1)
                            plt.plot(x,y2,label = PT1,color = color2)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确的三角函数,乘号不能省略")
                    elif CB2 == '圆':
                        if re.findall('[2](.+)[($]', PT1)[0] == '-':
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确圆的方程,乘号不能省略")
                        else:
                            try:
                                yuan_x = -int(re.findall(r'x([-+]\d{1,})',PT1)[0])
                            except:
                                yuan_x = 0
                            try:
                                yuan_y = -int(re.findall(r'y([-+]\d{1,})',PT1)[0])
                            except:
                                yuan_y = 0
                            center = (yuan_x,yuan_y)
                            r = int(re.findall(r'=(\d{1,})',PT1)[0])**(1/2)
                            print(r)
                            x = np.linspace(center[0] - r, center[0] + r, 5000)
                            y1 = np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            y2 = -np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            plt.plot(x, y1, c=color2,label = PT1)
                            plt.plot(x, y2, c=color2)
 
                    else:
                        try:
                            plt.plot(x, eval(PT1),label = PT1,color = color2)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "非法表达式,乘号不能省略")
 
        #函数3
        checkBox3 = self.checkBox_3.isChecked()
        if checkBox3 == True:
            PT3 = self.plainTextEdit_8.toPlainText()
            if PT3 == '':
                QtWidgets.QMessageBox.critical(self, "错误", "请输入所需画图的公式")
            else:
                x3_1 = self.plainTextEdit_7.toPlainText()
                x3_2 = self.plainTextEdit_9.toPlainText()
                if x3_1 == '' or x3_2 =='':
                    QtWidgets.QMessageBox.critical(self, "错误", "请输入取值范围")
                else:
                    X.append(float(x3_1))
                    X.append(float(x3_2))
                    color3 = self.comboBox_7.currentText()
                    CB3 = self.comboBox_3.currentText()
                    if color3 == '红色':
                        color3 = 'red'
                    elif color3 == '蓝色':
                        color3 = 'blue'
                    elif color3 == '绿色':
                        color3 = 'green'
                    elif color3 == '紫色':
                        color3 = 'purple'
                    x = np.linspace(float(x3_1),float(x3_2), 1000)
                    if CB3 == '三角函数':
                        try:
                            y3= eval('np.'+PT3)
                            plt.plot(x,y3,label = PT3,color = color3)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确的三角函数,乘号不能省略")
                    elif CB3 == '圆':
                        if re.findall('[2](.+)[($]', PT3)[0] == '-':
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确圆的方程,乘号不能省略")
                        else:
                            try:
                                yuan_x = -int(re.findall(r'x([-+]\d{1,})',PT3)[0])
                            except:
                                yuan_x = 0
                            try:
                                yuan_y = -int(re.findall(r'y([-+]\d{1,})',PT3)[0])
                            except:
                                yuan_y = 0
                            center = (yuan_x,yuan_y)
                            r = int(re.findall(r'=(\d{1,})',PT3)[0])**(1/2)
                            print(r)
                            x = np.linspace(center[0] - r, center[0] + r, 5000)
                            y1 = np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            y2 = -np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            plt.plot(x, y1, c=color3,label = PT3)
                            plt.plot(x, y2, c=color3)
                    else:
                        try:
                            plt.plot(x, eval(PT3),label = PT3,color = color3)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "非法表达式,乘号不能省略")
                
        #函数4
        checkBox4 = self.checkBox_4.isChecked()
        if checkBox4 == True:
            PT4 = self.plainTextEdit_11.toPlainText()
            if PT4 == '':
                QtWidgets.QMessageBox.critical(self, "错误", "请输入所需画图的公式")
            else:
                x4_1 = self.plainTextEdit_10.toPlainText()
                x4_2 = self.plainTextEdit_12.toPlainText()
                if x4_1 == '' or x4_2 =='':
                    QtWidgets.QMessageBox.critical(self, "错误", "请输入取值范围")
                else:
                    X.append(float(x4_1))
                    X.append(float(x4_2))
                    color4 = self.comboBox_8.currentText()
                    CB4 = self.comboBox_4.currentText()
                    if color4 == '红色':
                        color4 = 'red'
                    elif color4 == '蓝色':
                        color4 = 'blue'
                    elif color4 == '绿色':
                        color4 = 'green'
                    elif color4 == '紫色':
                        color4 = 'purple'
                    x = np.linspace(float(x4_1),float(x4_2), 1000)
                    if CB4 == '三角函数':
                        try:
                            y4= eval('np.'+PT4)
                            plt.plot(x,y4,label = PT4,color =color4)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确的三角函数,乘号不能省略")
                    elif CB4 == '圆':
                        if re.findall('[2](.+)[($]', PT4)[0] == '-':
                            QtWidgets.QMessageBox.critical(self, "错误", "请输入正确圆的方程,乘号不能省略")
                        else:
                            try:
                                yuan_x = -int(re.findall(r'x([-+]\d{1,})',PT4)[0])
                            except:
                                yuan_x = 0
                            try:
                                yuan_y = -int(re.findall(r'y([-+]\d{1,})',PT4)[0])
                            except:
                                yuan_y = 0
                            center = (yuan_x,yuan_y)
                            r = int(re.findall(r'=(\d{1,})',PT4)[0])**(1/2)
                            print(r)
                            x = np.linspace(center[0] - r, center[0] + r, 5000)
                            y1 = np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            y2 = -np.sqrt(r**2 - (x-center[0])**2) + center[1]
                            plt.plot(x, y1, c=color4,label = PT4)
                            plt.plot(x, y2, c=color4)
                    else:
                        try:
                            plt.plot(x, eval(PT4),label = PT4,color =color4)
                            plt.legend('best')
                        except:
                            QtWidgets.QMessageBox.critical(self, "错误", "非法表达式,乘号不能省略")
        try:
            plt.legend(loc='best',fontsize = 10)
            # 设置坐标轴 gca() 获取坐标轴信息
            ax=plt.gca()
            # print(X)
            # print(min(X),max(X))
            plt.xlim(1.5*min(X),1.5*(max(X)))
            plt.ylim(1.5*min(X),1.5*(max(X)))
            # 使用.spines设置边框：x轴；将右边颜色设置为 none。
            # 使用.set_position设置边框位置：y=0的位置；（位置所有属性：outward，axes，data）
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
            # 移动坐标轴
            # 将 bottom 即是 x 坐标轴设置到 y=0 的位置。
            ax.xaxis.set_ticks_position('bottom')
            ax.spines['bottom'].set_position(('data',0))

            # 将 left 即是 y 坐标轴设置到 x=0 的位置。
            ax.yaxis.set_ticks_position('left')
            ax.spines['left'].set_position(('data',0))

            # 设置标签
            # ax.set_title(a,fontsize=20)
            plt.tight_layout()

            # 显示图像
            # plt.show()

            canvas = FigureCanvas(pixs)
            self.graphicscene = QtWidgets.QGraphicsScene()  # 第三步，创建一个QGraphicsScene，因为加载的图形（FigureCanvas）不能直接放到graphicview控件中，必须先放到graphicScene，然后再把graphicscene放到graphicview中
            self.graphicscene.addWidget(canvas)  # 第四步，把图形放到QGraphicsScene中，注意：图形是作为一个QWidget放到QGraphicsScene中的
            self.graphicsView.setScene(self.graphicscene) # 第五步，把QGraphicsScene放入QGraphicsView
            self.graphicsView.show()  # 最后，调用show方法呈现图形！Voila!!

        except :
            pass


if __name__ == "__main__":
    app = QApplication(sys.argv)
    action = Action()
    sys.exit(app.exec_())